package com.tdkj.service.financial.impl;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.tdkj.model.financial.BeanTrading;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.financial.IBeanFimamcialAmountChangeRecordService;
import com.tdkj.service.financial.IBeanTradingService;

@Component
public class BeanTradingServiceImpl extends BaseService implements
		IBeanTradingService {
	
	private IBeanFimamcialAmountChangeRecordService fimamcialAmountChangeRecordService;
	
	@Resource
	public void setFimamcialAmountChangeRecordService(
			IBeanFimamcialAmountChangeRecordService fimamcialAmountChangeRecordService) {
		this.fimamcialAmountChangeRecordService = fimamcialAmountChangeRecordService;
	}

	@Override
	public void cancel(Long id) throws ServiceException {
		
		BeanTrading bean = this.getBaseDao().findById(id, BeanTrading.class);
		bean.setState(2);
		
		fimamcialAmountChangeRecordService.createIn(bean.getUser().getId(), bean.getProvide(), "银币", bean.getId(), BeanTrading.class, "银币交换取消");
	}

	@Override
	public void create(Long userId, Integer provide, Integer demand) throws ServiceException {
		BeanUser user = this.getBaseDao().findById(userId, BeanUser.class);
		
		
		BeanTrading bean = new BeanTrading();
		bean.setProvide(provide);
		bean.setDemand(demand);
		bean.setDateTime(new Timestamp(System.currentTimeMillis()));
		bean.setUser(user);
		bean.setState(0);
		
		this.getBaseDao().save(bean);
		fimamcialAmountChangeRecordService.createOut(user.getId(), provide, "银币", bean.getId(), BeanTrading.class, "银币交换发布");
	}

	@Override
	public void transaction(Long id, Long toUserId) throws ServiceException {
		BeanTrading bean = this.getBaseDao().findById(id, BeanTrading.class);
		BeanUser toUser = this.getBaseDao().findById(toUserId, BeanUser.class);
		bean.setToUser(toUser);
		bean.setState(1);
		
		fimamcialAmountChangeRecordService.createIn(bean.getUser().getId(), bean.getDemand(), "金币", bean.getId(), BeanTrading.class, "交易成功");
		fimamcialAmountChangeRecordService.createOut(toUser.getId(), bean.getDemand(), "金币", bean.getId(), BeanTrading.class, "交易成功");
		fimamcialAmountChangeRecordService.createIn(toUser.getId(), bean.getProvide(), "银币", bean.getId(), BeanTrading.class, "交易成功");
		
	}
	
}
